/**
 * @author 
 * @description axios+cookie+element-ui 封装request
 *  axios封装request && 效验存储到cookie中的token
 */
import axios from 'axios'
import { Message } from 'element-ui'
import Vue from 'vue'


const instance = axios.create({
  baseURL: '',
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求拦截
 */
instance.interceptors.request.use(config => {
  //使用cookie 效验token
  if (Vue.$cookies.get('token')) {
    config.headers['Authorization'] = "bearer " + Vue.$cookies.get('token') // 请求头带上token
  }
  return config
}, error => {
  Message.error('网络请求超时，请稍后重试...')
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
instance.interceptors.response.use(response => {
  if (response.data && response.status === 200) {
    return response.data
  } else {
    return response
  }
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        Message.error('请求错误')
        break
      case 401:
        Message.error('授权过期，请重新登录')
        break
      case 403:
        Message.error('拒绝访问')
        break
      case 404:
        Message.error(`请求地址出错: ${err.response.config.url}`)
        break
      case 408:
        Message.error('请求超时')
        break
      case 500:
        Message.error('服务器内部错误')
        break
      case 501:
        Message.error('服务未实现')
        break
      case 502:
        Message.error('网关错误')
        break
      case 503:
        Message.error('服务不可用')
        break
      case 504:
        Message.error('网关超时')
        break
      case 505:
        Message.error('HTTP版本不受支持')
        break
      default:
        Message.error('未知错误，请联系管理员')
    }
  }
  return Promise.reject(err)
})

class http {
  static async get (url, params) {
    return res
  }
  static async post (url, params) {
    let res = await instance.post(url, params)
    return res
  }
}

export default http

